package org.jflame.auth.web;

import org.jflame.auth.LoginUser;
import org.jflame.auth.authz.MultiUrlPermit;
import org.jflame.auth.context.UserContextHolder;
import org.jflame.commons.util.StringHelper;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.jstl.core.ConditionalTagSupport;

/**
 * 权限判断标签
 * <p>
 * 属性:<br>
 * pm表示权限标识; <br>
 * roles表示角色标识,多个角色可用,隔开;<br>
 * rootRoles表示根角色标识,即根角色下的所有子角色都有权限,多个角色可用,隔开;<br>
 * <p>
 * 1.pm和roles都不设置时，表示所有用户都有权限<br>
 * 2.pm和roles都设置时 条件是or关系,即有一个为true即有权限
 * <p>
 * 使用示例： {@code <jfa:auth pm="SCHOOL_ADD"><a href="#">add school</a></jfa:auth>} <br>
 * 判断结果的存储,在循环语句中需要判断同一权限时，推荐循环外判断一次然后存储结果 :<br>
 * {@code 
 * <jfa:auth var="pm_add" pm="SCHOOL_ADD"><a href="#">add school</a></jfa:auth>}
 * 
 * @author charles.zhang
 */
public class IfAuthTag extends ConditionalTagSupport {

    private static final long serialVersionUID = 1L;

    private String pm;
    private String roles;

    public String getPm() {
        return pm;
    }

    public void setPm(String pm) {
        this.pm = pm;
    }

    public String getRoles() {
        return roles;
    }

    public void setRoles(String roles) {
        this.roles = roles;
    }

    @Override
    protected boolean condition() throws JspTagException {
        boolean hasPm = false,hasRole = false;
        LoginUser curUser = UserContextHolder.getContext()
                .getUser();
        if (StringHelper.isNotEmpty(pm)) {
            String[] strPerms = StringHelper.split(pm);
            MultiUrlPermit[] userPerms = new MultiUrlPermit[strPerms.length];
            for (int i = 0; i < strPerms.length; i++) {
                userPerms[i] = new MultiUrlPermit(strPerms[i]);
            }
            hasPm = curUser.isAnyPermitted(userPerms);
        }
        if (!hasPm && StringHelper.isNotEmpty(roles)) {
            String[] roleCodes = StringHelper.split(roles);
            hasRole = curUser.hasAnyRole(roleCodes);
        }
        return hasPm || hasRole;
    }

}
